import { ConfigureService } from '@app/configure';
import { JwtVerifyService } from '@app/jwt-verify';
import { CanActivate, ExecutionContext, Inject, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
import { ReqAttrs } from '../../constant';
import { USER_SOURCE } from 'constant/USER_SOURCE';

@Injectable()
export class AuthGuard implements CanActivate {
	@Inject()
	private readonly config:ConfigureService
	@Inject()
	private readonly jwt:JwtVerifyService


	async canActivate(
		context: ExecutionContext,
	): Promise<boolean> {
		let request = context.switchToHttp().getRequest()

		const route = request.route
		let path:string = route.path
		const whites = this.config.get<string[]>('whites')

		const routePrefix = this.config.get('API_PRE_FIX')
		if(routePrefix != undefined && routePrefix.length > 0) {
			path = path.substring(routePrefix.length + 1)
		}



		const isWhite = whites.includes(path)


		const token = request.headers.authorization
		
		if(token) {
			const payload = this.jwt.verify(token)


			if(payload == null) {

				if(!isWhite) {
					return false
				}

			}else {
				request[ReqAttrs.USER_ID] = payload.key
			}

			
			
			
		}

		if(request.headers['client-type']) {
			request[ReqAttrs.IS_WX] = request.headers['client-type'] == 'wx'
			request[ReqAttrs.IS_ALI] = request.headers['client-type'] == 'ali'
			request[ReqAttrs.CLIENT_SOURCE] = request[ReqAttrs.IS_WX] ? USER_SOURCE.WX : USER_SOURCE.ALI
		}

		return true;
	}
}
